<template>
  <div class="message-process">
    <el-card class="process-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索消息标题/内容"
              class="search-input"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" link @click="showAdvancedSearch = !showAdvancedSearch">
              {{ showAdvancedSearch ? '收起' : '展开' }}高级搜索
              <el-icon>
                <component :is="showAdvancedSearch ? 'ArrowUp' : 'ArrowDown'" />
              </el-icon>
            </el-button>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleExport">
              <el-icon><Download /></el-icon>导出记录
            </el-button>
          </div>
        </div>

        <!-- 高级搜索表单 -->
        <el-collapse-transition>
          <div v-show="showAdvancedSearch" class="advanced-search">
            <el-form :model="searchForm" label-width="100px" class="search-form">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="消息类型">
                    <el-select v-model="searchForm.type" placeholder="请选择消息类型" clearable>
                      <el-option
                        v-for="item in messageTypes"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="处理状态">
                    <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable>
                      <el-option
                        v-for="item in processStatus"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="处理时间">
                    <el-date-picker
                      v-model="searchForm.timeRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" class="search-buttons">
                  <el-button @click="resetSearch">重置</el-button>
                  <el-button type="primary" @click="handleAdvancedSearch">搜索</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-transition>
      </template>

      <!-- 处理记录列表 -->
      <el-table
        :data="processList"
        border
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="process-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in props.row.processRecords"
                  :key="index"
                  :type="getTimelineItemType(activity.status)"
                  :timestamp="activity.createTime"
                >
                  <div class="timeline-content">
                    <div class="timeline-title">
                      {{ getStatusLabel(activity.status) }}
                      <el-tag size="small" :type="getStatusTagType(activity.status)">
                        {{ activity.operator }}
                      </el-tag>
                    </div>
                    <div class="timeline-desc" v-if="activity.comment">
                      {{ activity.comment }}
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="消息标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="消息类型" width="120">
          <template #default="scope">
            <el-tag :type="getMessageTypeTag(scope.row.type)">
              {{ getMessageTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentHandler" label="当前处理人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleProcess(scope.row)"
              v-if="canProcess(scope.row)"
            >处理</el-button>
            <el-button
              type="primary"
              link
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              type="primary"
              link
              @click="handleRemind(scope.row)"
              v-if="canRemind(scope.row)"
            >提醒</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理消息"
      width="600px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="processForm.status" placeholder="请选择处理状态">
            <el-option
              v-for="item in nextProcessStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理意见" prop="comment">
          <el-input
            v-model="processForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入处理意见"
          />
        </el-form-item>
        <el-form-item label="下一步处理人" prop="nextHandler" v-if="needNextHandler">
          <el-select
            v-model="processForm.nextHandler"
            placeholder="请选择下一步处理人"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            >
              <span>{{ user.name }}</span>
              <span class="user-department">{{ user.department }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess" :loading="processing">
          提交
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="消息详情"
      width="800px"
    >
      <div class="message-detail">
        <div class="detail-header">
          <h3>{{ currentMessage.title }}</h3>
          <div class="detail-tags">
            <el-tag :type="getMessageTypeTag(currentMessage.type)">
              {{ getMessageTypeLabel(currentMessage.type) }}
            </el-tag>
            <el-tag :type="getStatusTagType(currentMessage.status)">
              {{ getStatusLabel(currentMessage.status) }}
            </el-tag>
          </div>
        </div>
        <div class="detail-content">
          <div class="content-item">
            <span class="label">消息内容：</span>
            <div class="value">{{ currentMessage.content }}</div>
          </div>
          <div class="content-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ currentMessage.createTime }}</span>
          </div>
          <div class="content-item">
            <span class="label">创建人：</span>
            <span class="value">{{ currentMessage.creator }}</span>
          </div>
          <div class="content-item">
            <span class="label">当前处理人：</span>
            <span class="value">{{ currentMessage.currentHandler }}</span>
          </div>
        </div>
        <div class="detail-timeline">
          <h4>处理记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in currentMessage.processRecords"
              :key="index"
              :type="getTimelineItemType(activity.status)"
              :timestamp="activity.createTime"
            >
              <div class="timeline-content">
                <div class="timeline-title">
                  {{ getStatusLabel(activity.status) }}
                  <el-tag size="small" :type="getStatusTagType(activity.status)">
                    {{ activity.operator }}
                  </el-tag>
                </div>
                <div class="timeline-desc" v-if="activity.comment">
                  {{ activity.comment }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Download, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import {
  getMessageProcessList,
  processMessage,
  getMessageDetail,
  searchUsers,
  exportProcessRecords,
  sendProcessReminder
} from '@/api/message'

// 数据加载状态
const loading = ref(false)
const processing = ref(false)
const userSearchLoading = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')
const showAdvancedSearch = ref(false)
const searchForm = reactive({
  type: '',
  status: '',
  timeRange: []
})

// 对话框显示状态
const processDialogVisible = ref(false)
const viewDialogVisible = ref(false)

// 列表数据
const processList = ref([])
const currentMessage = ref({})
const userOptions = ref([])

// 消息类型
const messageTypes = [
  { value: 'notification', label: '通知' },
  { value: 'task', label: '任务' },
  { value: 'warning', label: '警告' },
  { value: 'system', label: '系统' }
]

// 处理状态
const processStatus = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'rejected', label: '已驳回' },
  { value: 'cancelled', label: '已取消' }
]

// 处理表单
const processFormRef = ref(null)
const processForm = reactive({
  status: '',
  comment: '',
  nextHandler: ''
})

// 处理表单验证规则
const processRules = {
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  comment: [{ required: true, message: '请输入处理意见', trigger: 'blur' }],
  nextHandler: [{ required: true, message: '请选择下一步处理人', trigger: 'change' }]
}

// 计算属性
const needNextHandler = computed(() => {
  return ['processing'].includes(processForm.status)
})

const nextProcessStatus = computed(() => {
  const currentStatus = currentMessage.value.status
  switch (currentStatus) {
    case 'pending':
      return processStatus.filter(s => ['processing', 'rejected', 'cancelled'].includes(s.value))
    case 'processing':
      return processStatus.filter(s => ['completed', 'rejected'].includes(s.value))
    default:
      return []
  }
})

// 初始化数据
onMounted(() => {
  fetchProcessList()
})

// 获取处理记录列表
const fetchProcessList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      query: searchQuery.value,
      ...searchForm,
      startTime: searchForm.timeRange?.[0],
      endTime: searchForm.timeRange?.[1]
    }
    const res = await getMessageProcessList(params)
    processList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取处理记录列表失败:', error)
    ElMessage.error('获取处理记录列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1
  fetchProcessList()
}

const handleAdvancedSearch = () => {
  pageNum.value = 1
  fetchProcessList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    type: '',
    status: '',
    timeRange: []
  })
  handleAdvancedSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProcessList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchProcessList()
}

// 处理消息
const handleProcess = async (row) => {
  currentMessage.value = row
  processForm.status = ''
  processForm.comment = ''
  processForm.nextHandler = ''
  processDialogVisible.value = true
}

// 查看消息
const handleView = async (row) => {
  try {
    const res = await getMessageDetail(row.id)
    currentMessage.value = res.data
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取消息详情失败:', error)
    ElMessage.error('获取消息详情失败')
  }
}

// 提醒处理
const handleRemind = (row) => {
  ElMessageBox.confirm('确定要发送处理提醒吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await sendProcessReminder(row.id)
      ElMessage.success('提醒发送成功')
    } catch (error) {
      console.error('发送提醒失败:', error)
      ElMessage.error('发送提醒失败')
    }
  })
}

// 提交处理
const submitProcess = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    processing.value = true
    
    await processMessage({
      messageId: currentMessage.value.id,
      ...processForm
    })
    
    ElMessage.success('处理成功')
    processDialogVisible.value = false
    fetchProcessList()
  } catch (error) {
    console.error('处理消息失败:', error)
    ElMessage.error(error.message || '处理失败')
  } finally {
    processing.value = false
  }
}

// 搜索用户
const searchUsers = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      const res = await searchUsers({ query })
      userOptions.value = res.data
    } catch (error) {
      console.error('搜索用户失败:', error)
    } finally {
      userSearchLoading.value = false
    }
  } else {
    userOptions.value = []
  }
}

// 导出记录
const handleExport = async () => {
  try {
    const params = {
      query: searchQuery.value,
      ...searchForm,
      startTime: searchForm.timeRange?.[0],
      endTime: searchForm.timeRange?.[1]
    }
    const res = await exportProcessRecords(params)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '消息处理记录.xlsx'
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出记录失败:', error)
    ElMessage.error('导出记录失败')
  }
}

// 工具函数
const getMessageTypeLabel = (type) => {
  return messageTypes.find(t => t.value === type)?.label || type
}

const getMessageTypeTag = (type) => {
  const typeMap = {
    notification: '',
    task: 'success',
    warning: 'warning',
    system: 'info'
  }
  return typeMap[type] || ''
}

const getStatusLabel = (status) => {
  return processStatus.find(s => s.value === status)?.label || status
}

const getStatusTagType = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    rejected: 'danger',
    cancelled: 'info'
  }
  return statusMap[status] || ''
}

const getTimelineItemType = (status) => {
  const typeMap = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    rejected: 'danger',
    cancelled: 'info'
  }
  return typeMap[status] || ''
}

const canProcess = (row) => {
  return ['pending', 'processing'].includes(row.status)
}

const canRemind = (row) => {
  return ['pending', 'processing'].includes(row.status)
}
</script>

<style lang="scss" scoped>
.message-process {
  padding: 20px;

  .process-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 16px;

        .search-input {
          width: 200px;
        }
      }
    }

    .advanced-search {
      margin-bottom: 16px;
      padding: 16px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .search-form {
        .search-buttons {
          display: flex;
          justify-content: center;
          gap: 16px;
          margin-top: 16px;
        }
      }
    }

    .process-timeline {
      padding: 16px;

      .timeline-content {
        .timeline-title {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;
        }

        .timeline-desc {
          color: #666;
          font-size: 14px;
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .message-detail {
    .detail-header {
      margin-bottom: 24px;

      h3 {
        margin: 0 0 16px;
        font-size: 18px;
      }

      .detail-tags {
        display: flex;
        gap: 8px;
      }
    }

    .detail-content {
      margin-bottom: 24px;

      .content-item {
        margin-bottom: 16px;

        .label {
          color: #666;
          margin-right: 8px;
        }

        .value {
          color: #333;
        }
      }
    }

    .detail-timeline {
      h4 {
        margin: 0 0 16px;
        font-size: 16px;
      }
    }
  }
}

.user-department {
  margin-left: 8px;
  color: #999;
  font-size: 12px;
}
</style> 